package org.gpf.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gpf.factory.DAOFactory;
import org.gpf.vo.User;

@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {

	private String username = null; 		// 从JSP页面通过get提交的用户名和密码
	private String password = null;
	private String path = "login.jsp"; 		// 最后servlet跳转的路径
	private List<String> info; 				// 保存错误信息和用户登录成功的信息

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		username = request.getParameter("username");
		password = request.getParameter("password");
		info = new ArrayList<String>();
		if (username == null || "".equals(username))
			info.add("用户名不能为空!");
		if (password == null || "".equals(password))
			info.add("密码不能为空！");

		/* 如果用户输入了用户名和密码，则不会出现错误信息,发送到服务器验证 */
		if (info.size() == 0) {
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			if (DAOFactory.getIUserDAOInstance().findLogin(user)){
				info.add("登录成功，2秒内将跳转到登录成功页面。如果没有跳转请点击<a href='login_success.jsp'>这里</a>");
				request.getSession().setAttribute("username", username); // 向session中设置用户名
				response.setHeader("refresh","2;URL=login_success.jsp") ;
			}
			else{
				info.add("登录失败，错误的用户名或者密码！");
				request.setAttribute("info", info); // 将信息保存在request中，通过服务端跳转发往jsp
				request.getRequestDispatcher(path).forward(request, response);
			}
		}
	}

}
